package com.urbainski.componentes.utils{
	
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import mx.utils.ObjectUtil;
	
	public class ObjectUtils {
		
		public static function getInstancia(nomeClasse : String) : Object {
			
			var ClassReference:Class 		= getDefinitionByName(nomeClasse) as Class;
			var retorno : Object			= new ClassReference();
			
			return retorno;
			
		}
		
		public static function getInstanciaObjeto(obj : Object) : Object {
			
			var nomeClasse : String = getQualifiedClassName(obj);
			return getInstancia(nomeClasse);
		}
		
		public static function copyProperties(objOrigem : Object, objDestino : Object) : void {
			var arrProperties : Array = ObjectUtil.getClassInfo(objOrigem).properties;
			
			for (var i : int = 0; i < arrProperties.length; i++){
				var property : String = arrProperties[i];
				if (objDestino.hasOwnProperty(property)){
					objDestino[property] = objOrigem[property]; 
				}	
			}	
		}
		
		
		public static function copyNotNullProperties(objOrigem : Object, objDestino : Object) : void {
			var arrProperties : Array = ObjectUtil.getClassInfo(objOrigem).properties;
			
			for (var i : int = 0; i < arrProperties.length; i++){
				var property : String = arrProperties[i];
				if (objDestino.hasOwnProperty(property)){
					if (objOrigem[property] != null){
						objDestino[property] = objOrigem[property];
					} 
				}	
			}	
		}
		
		public static function getLength(o:Object):uint {
			var len:uint = 0;
			
			for (var item:* in o) {
				if (item != "mx_internal_uid") {
					len++;
				}
			}
			
			return len;
		}
		
		
		public static function apply(config:Object, target:Object, strongTyped:Boolean = true, reportErrors:Boolean = false):void {
			if (!config)
				return; 
			for (var p:String in config) {
				trace ('Applying property "' + p + '": "' + config[p]);
				if (config[p] != null && config[p] != undefined){ // não aplica nulls e NaNs
					if (strongTyped){ // verifica se o destino possui a propriedade
						if (target.hasOwnProperty(p)){ 
							target[p] = config[p];
						} else if (reportErrors){
							throw new Error('Propriedade "' + p + '" não existe');
						}
					} else {
						target[p] = config[p];
					}
				}
			}		
		}
		
	}
}	
